import axios, { type AxiosResponse } from "axios";
import { ElMessage, ElMessageBox } from "element-plus";
import pinia from "@/stores/index";
import { useUserStore } from "@/stores/user";

const service = axios.create({
  baseURL: import.meta.env.VITE_API_URL,
  timeout: 10000,
});

service.interceptors.request.use(
  (config) => {
    const userStore = useUserStore(pinia);
    (config.headers as any).token = userStore.token;
    return config;
  },
  (e) => {
    return Promise.reject(e);
  }
);

service.interceptors.response.use(
  (res) => {
    if (res.data.code === 20000 || res.data.code === 200) {
      return res.data.data;
    } else {
      ElMessage.error(res.data.message);
      return Promise.reject(res.data);
    }
  },

  function (e) {
    ElMessage.error("请求错误:", e);
    return Promise.reject(e);
  }
);

export default service;
